package com.yc.util;

import com.yc.service.ServiceException;

import java.util.ArrayList;
import java.util.List;

public class PageUtil {
    private Integer pageSize; //页面尺寸
    private Integer pageNum;  //设置查询的页码

    /**
     * 初始化，设置分页尺寸及查询页码
     * @param pageSize
     */
    public PageUtil(int pageNum,int pageSize){
        this.pageSize=pageSize;
        this.pageNum=pageNum;
    }

    public <T> List<T> get(List<T> list) throws ServiceException {
        try {
            checkList(list);
            List<T> newlist=new ArrayList<>();
            int num=pageNum*pageSize>list.size()?list.size():pageNum*pageSize;
            for ( int i = (pageNum-1)*pageSize; i < num; i++ ) {
                newlist.add(list.get(i));
            }
            return newlist;
        } catch ( ServiceException e ) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 检测list是否符合条件
     * @param list
     * @return
     */
    public Boolean checkList(List list) throws ServiceException {
        if ( list==null||list.size()==0 ){
            throw new ServiceException("传入的集合为空，请确定后重试");
        }
        if ( list.size()<(pageNum-1)*pageSize ){
            throw new ServiceException("集合的长度错误，请检查页码和页面尺寸后重新输入");
        }
        return true;
    }
}
